package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.AreaService;
import co.gov.medellin.ssti.sub.model.service.AtributosService;
import co.gov.medellin.ssti.sub.model.service.ConsultasService;
import co.gov.medellin.ssti.sub.model.service.ProgramaService;
import co.gov.medellin.ssti.sub.model.service.SubprogramaService;
import co.gov.medellin.ssti.sub.model.service.ValidacionService;
import co.gov.medellin.ssti.sub.model.vo.AreaVO;
import co.gov.medellin.ssti.sub.model.vo.ProgramaVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;
import co.gov.medellin.ssti.sub.web.form.SubprogramaForm;

@Component
public class GuardarSubprogramaAction extends Action {
	@Autowired
	AreaService areaServiceImpl;
	@Autowired
	AtributosService atributosServiceImpl;
	@Autowired
	SubprogramaService subprogramaServiceImpl;
	@Autowired
	ConsultasService consultasServiceImpl;
	@Autowired
	ProgramaService programaServiceImpl;
	@Autowired
	ValidacionService validacionServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			SubprogramaForm objSubForm = (SubprogramaForm) form;
			HttpSession session = request.getSession();

			try {
				// Proceso para validar si el usuario tiene permisos para crear
				// el beneficio.
				UserVO objUservo = (UserVO) request.getSession().getAttribute(
						"userInfo");
				Long lnCodeUser = objUservo.getCode();
				String strNameGroup = objUservo.getUserGroupName();

				String strCodeProg = objSubForm.getCodePrograma();
				ProgramaVO objProgVo = new ProgramaVO();
				objProgVo.setCodePrograma(strCodeProg);
				AreaVO objAreaVO = areaServiceImpl.findAreaByProg(strCodeProg);
				objSubForm.setSubsecretaria(Long.toString(objAreaVO.getCode()));

				Collection<ProgramaVO> cPrograma = null;
				cPrograma = programaServiceImpl.findProgramaByCriteria(
						objProgVo, strNameGroup, lnCodeUser,
						objUservo.getCodeArea());

				// Fin del proceso

				if (cPrograma != null && cPrograma.size() != 0) {

					boolean existe = false;

					if (objSubForm.getSubprograma() != null
							&& objSubForm.getCodePrograma() != null) {
						existe = validacionServiceImpl.validaSubprg(objSubForm
								.getSubprograma().trim());
					}

					if (!existe) {
						// Proceso para la auditoria
						UserVO user = (UserVO) request.getSession()
								.getAttribute("userInfo");
						String terminalAddress = request.getRemoteAddr();
						String strTerminal = ("WEB=" + terminalAddress);
						Calendar c = Calendar.getInstance();
						SimpleDateFormat dateFormat = new SimpleDateFormat(
								"dd/MM/yyyy");
						// Fin del proceso

						String strDesde = objSubForm.getDesde();
						String strHasta = objSubForm.getHasta();

						String paraEmpresa = objSubForm.getParaEmpresa();

						if ((strDesde != null && strDesde.length() > 0)
								&& (strHasta != null && strHasta.length() > 0)) {
							objSubForm.setDesde(strDesde);
							objSubForm.setHasta(strHasta);
						}

						// almacena el subprograma
						int iOutput = subprogramaServiceImpl.insertBeneficio(
								objSubForm, user.getName(), strTerminal,
								dateFormat.format(c.getTime()));
						String strMaxCode = null;

						if (iOutput > 0) {
							session.setAttribute("mensajes",
									"El subprograma fue creado satisfactoriamente.");
							strMaxCode = Integer.toString(iOutput);// subprogramaServiceImpl.findMaxCodigo();
							session.setAttribute("subpro", strMaxCode);
						} else {
							session.setAttribute("mensajes",
									"El Beneficio no se pudo crear.");
						}

					} else {
						session.setAttribute("mensajes",
								"El Beneficio ya existe...!!!");
						request.setAttribute("secretaria",
								objSubForm.getSubsecretaria());
						return mapping.findForward("fail");
					}
				} else {
					response.sendRedirect(request.getContextPath()
							+ "/admin/tile/invalidatedResource.jsp");
				}

			} catch (DAOException e) {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSUB - cwsub ********/");
				session.setAttribute("mensajes",
						"El Beneficio no se pudo crear.");
			}
		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}
		return mapping.findForward("success");
	}
}